package com.bawei.live.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.live.intent.LiveViewIntent
import com.bawei.live.model.LiveRepository
import com.bawei.live.state.LiveUiState
import com.blankj.utilcode.util.ToastUtils.cancel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: Lin Liu
 * @CreateTime: 2025年02月17日 15:59:40
 * @Description:
 */
@HiltViewModel
class LiveViewModel @Inject constructor(private val repository: LiveRepository): BaseViewModel<LiveViewIntent>(){
    private val _uiState = MutableStateFlow<LiveUiState>(LiveUiState.LoadEmpty)
    val uiState: StateFlow<LiveUiState> = _uiState

    override fun dispatchIntent(intent: LiveViewIntent) {
        when (intent) {
            is LiveViewIntent.LoadRecommendSimpleVideo -> loadRecommendSimpleVideo(intent.page, intent.pageSize)
        }
    }

    private fun loadRecommendSimpleVideo(page: Int, pageSize: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.getRecommendVideo(page, pageSize).collect{ list ->
                    if (list.isNotEmpty()){
                        _uiState.value = LiveUiState.LoadSimpleVideoSuccess(list)
                    } else{
                        _uiState.value = LiveUiState.LoadSimpleVideoFail("没有推荐视频")
                    }
                }
            } catch (e:Exception){
                e.printStackTrace()
                _uiState.value = LiveUiState.LoadSimpleVideoFail("请求失败！！")
            } finally {
                cancel()
            }
        }

    }


}